package com.lry.crawlers.cartoon.processor;

import com.lry.crawlers.cartoon.entity.CartoonVariable;
import com.lry.crawlers.cartoon.service.CartoonService;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

import java.util.*;

public class CartoonProcessor implements PageProcessor {

    public CartoonVariable cartoonVariable;

    public CartoonService cartoonService;

    public CartoonProcessor(){
    }

    public CartoonProcessor(CartoonVariable cartoonVariable, CartoonService cartoonService){
        this.cartoonVariable = cartoonVariable;
        this.cartoonService = cartoonService;
    }



    private Site site = Site.me()
            .setSleepTime(1)//采集间隔时间
            .setTimeOut(1000*10)//超时时间
            .setRetrySleepTime(3000)//重试时间
            .setRetryTimes(3);//重试次数

    public Site getSite() {
        return site;
    }
    

    //解析页面
    public void process(Page page) {

        String url = page.getUrl().toString();
        String[] titless = cartoonVariable.getTitle().split("-!-");
        List<String> titlee = page.getHtml().xpath(titless[0]).regex(titless.length !=1 ? titless[1] : ".+").all();
        String[] contentss = cartoonVariable.getContent().split("-!-");
        List<String> contentt = page.getHtml().xpath(contentss[0]).regex(contentss.length !=1 ? contentss[1] : ".+").all();
        String[] cartoontitlelss = cartoonVariable.getCartoonTitle().split("-!-");
        List<String> cartoontitlell = page.getHtml().xpath(cartoontitlelss[0]).regex(cartoontitlelss.length !=1 ? cartoontitlelss[1] : ".+").all();

        //漫画搜索
        if(cartoontitlell.size()!=0){
            List<String> title = new ArrayList<String>();
            try {
                //获取漫画信息：title，desc,author,cartoonType,cover,CartoonUrl,CartoonId
                String[] titles = cartoonVariable.getCartoonTitle().split("-!-");
                title = page.getHtml().xpath(titles[0]).regex(titles.length != 1 ? titles[1] : ".+").all();
            }catch (Exception e){}

            //通过漫画标签判断搜索内容是否存在
            if(title.size()!=0){
                String[] cartoonUrls = cartoonVariable.getCartoonUrl().split("-!-");
                String[] pageUrls = cartoonVariable.getPage().split("-!-");
                List<String> cartoonUrl = page.getHtml().xpath(cartoonUrls[0]).regex(cartoonUrls.length !=1 ? cartoonUrls[1] : ".+").all();
                String pageUrl = page.getHtml().xpath(pageUrls[0]).regex(pageUrls.length !=1 ? pageUrls[1] : ".+").get();
                //获取漫画章节与内容的对应的chapterId,并处理无域名url

                if(!cartoonUrl.get(0).contains("http")){
                    List<String> cartoonUrll = new ArrayList<>();
                    cartoonUrl.forEach(str -> {
                        cartoonUrll.add(cartoonVariable.getProtocol()+"://"+ cartoonVariable.getUrl()+str);
                    });
                    cartoonUrl = cartoonUrll;
                }
                List<Integer> duplicates = cartoonService.removeDuplicates(title);
                for (int i : duplicates) {
                    cartoonUrl.set(i,null);
                }
                while (cartoonUrl.remove(null));

                if (cartoonUrl.size() != 0) {
                    //把漫画链接加入爬取列表
                    page.addTargetRequests(cartoonUrl);
                }
                //把漫画下一页加入爬取列表
                if (pageUrl != null) {
                    if (pageUrl.contains("http")) {
                    }else if(pageUrl.contains("/")){
                        pageUrl = cartoonVariable.getProtocol() + "://" + cartoonVariable.getUrl() + pageUrl;
                    }else if(!pageUrl.contains("javascript")){
                        pageUrl = url + pageUrl;
                    }
                    page.addTargetRequest(pageUrl);
                }
            }
        }
        //漫画章节
        else if (titlee.size()!=0){
            //获取漫画章节信息：chapterTitle，chapterUrl，chapterId
            //获取漫画信息：title，desc,author,cartoonType,cover,CartoonUrl,CartoonId
            String[] titles = cartoonVariable.getTitle().split("-!-");
            String[] descs = cartoonVariable.getDescs().split("-!-");
            String[] authors = cartoonVariable.getAuthor().split("-!-");
            String[] cartoonTypes = cartoonVariable.getCartoonType().split("-!-");
            String[] covers = cartoonVariable.getCover().split("-!-");
            String[] chapterTitles = cartoonVariable.getChapterTitle().split("-!-");
            String[] chapterUrls = cartoonVariable.getChapterUrl().split("-!-");
            String[] updateTimes = cartoonVariable.getUpdateTime().split("-!-");
            List<String> title = page.getHtml().xpath(titles[0]).regex(titles.length !=1 ? titles[1] : ".+").all();
            List<String> desc = page.getHtml().xpath(descs[0]).regex(descs.length !=1 ? descs[1] : ".+").all();
            List<String> author = page.getHtml().xpath(authors[0]).regex(authors.length !=1 ? authors[1] : ".+").all();
            List<String> cartoonType = page.getHtml().xpath(cartoonTypes[0]).regex(cartoonTypes.length !=1 ? cartoonTypes[1] : ".+").all();
            List<String> cover = page.getHtml().xpath(covers[0]).regex(covers.length !=1 ? covers[1] : ".+").all();
            List<String> chapterTitle = page.getHtml().xpath(chapterTitles[0]).regex(chapterTitles.length !=1 ? chapterTitles[1] : ".+").all();
            List<String> chapterUrl = page.getHtml().xpath(chapterUrls[0]).regex(chapterUrls.length !=1 ? chapterUrls[1] : ".+").all();
            List<String> updateTime = page.getHtml().xpath(updateTimes[0]).regex(updateTimes.length !=1 ? updateTimes[1] : ".+").all();
            if(chapterTitles.length ==3){
                String[] splitTitl = chapterTitles[2].split(",");
                if(splitTitl.length ==1){
                    chapterTitle = chapterTitle.subList(Integer.parseInt(splitTitl[0]),chapterTitle.size());
                }else{
                    chapterTitle = chapterTitle.subList(Integer.parseInt(splitTitl[0]),Integer.parseInt(splitTitl[1]));

                }
            }
            if(chapterUrls.length == 3){
                String[] splitUrls = chapterUrls[2].split(",");
                if(splitUrls.length ==1){
                    chapterUrl = chapterUrl.subList(Integer.parseInt(splitUrls[0]),chapterUrl.size());
                }else{
                    chapterUrl = chapterUrl.subList(Integer.parseInt(splitUrls[0]),Integer.parseInt(splitUrls[1]));
                }
            }

            List<String> chapterId = new ArrayList<String>();

            //判断是否存在
            if (title.size() == 0) {
                title.add(" ");
            }
            if (author.size() == 0) {
                author.add(" ");
            }
            if (cartoonType.size() == 0) {
                cartoonType.add(" ");
            }
            if (cover.size() == 0) {
                cover.add(" ");
            }
            if (updateTime.size() == 0) {
                updateTime.add(" ");
            }
            if (desc.size() == 0) {
                desc.add(" ");
            }
            if (chapterTitle.size() == 0) {
                chapterTitle.add(" ");
            }
            if (chapterUrl.size() == 0) {
                chapterUrl.add(" ");
            }
             Boolean duplicate = cartoonService.removeDuplicate(title.get(0));
            if(!duplicate) {
                //获取对应的cartoonId
                String[] chapterUrl1 = chapterUrl1 = chapterUrl.get(0).split("/");
                String cartoonId = chapterUrl1[chapterUrl1.length - 2].replace(".html", "");
                //获取漫画章节与内容的对应的chapterId,并处理无域名url
                if (!chapterUrl.get(0).contains("http")) {
                    ArrayList<String> listUrl = new ArrayList<String>();
                    chapterUrl.forEach(str -> {
                        listUrl.add(cartoonVariable.getProtocol() + "://" + cartoonVariable.getUrl() + str);
                        String[] st = str.split("/");
                        chapterId.add(st[st.length - 1].replace(".html", ""));
                    });
                    chapterUrl = listUrl;
                } else {
                    chapterUrl.forEach(u -> {
                        String[] st = u.split("/");
                        chapterId.add(st[st.length - 1].replace(".html", ""));
                    });
                }
                if(!cover.get(0).contains("http")){
                    cover.set(0,cartoonVariable.getProtocol() + "://" + cartoonVariable.getUrl() + cover.get(0));
                }
                //创建储存Map数据，用于业务处理
                Map<String, Object> chapterMap = new HashMap<>();
                chapterMap.put("key", "cartoonChapter");
                chapterMap.put("title", title.get(0));
                chapterMap.put("desc", desc.get(0));
                chapterMap.put("author", author.get(0));
                chapterMap.put("updateTime", updateTime.get(0));
                chapterMap.put("cartoonType", cartoonType.get(0));
                chapterMap.put("cover", cover.get(0));
                chapterMap.put("chapterTitle", chapterTitle);
                chapterMap.put("chapterId", chapterId);
                chapterMap.put("cartoonId", cartoonId);
                chapterMap.put("updateUrl", url);
                chapterMap.put("id", cartoonVariable.getId());
                //提交数据，给Pipeline处理
                page.putField("data", chapterMap);
                //把漫画章节链接加入爬取列表
                page.addTargetRequests(chapterUrl);
            }
        }
        //漫画内容
        else if(contentt.size()!=0){
            //获取漫画内容信息：content

            String[] contents = cartoonVariable.getContent().split("-!-");

            List<String> content = page.getHtml().xpath(contents[0]).regex(contents.length !=1 ? contents[1] : ".+").all();

            //获取漫画内容与章节对应的cartoonId
            String[] listUrl =  page.getUrl().toString().split("/");
            String chapterId = listUrl[listUrl.length-1].replace(".html","");
            String cartoonId = listUrl[listUrl.length-2].replace(".html","");
            if(cartoonVariable.getContentPage().length()!=0){
                List<String> list= new ArrayList<>();
                Spider.create(new CartoonContentProcessor(cartoonVariable,list))
                        //设置爬取数据的地址
                        .addUrl(url)
                        //设置多线程
                        .thread(5)
                        //执行爬虫
                        .run();
                    content=list;

            }
            //创建储存Map数据，用于业务处理
            Map<String,Object> map = new HashMap<>();
            map.put("key","content");
            map.put("content",content);
            map.put("chapterId",chapterId);
            map.put("cartoonId",cartoonId);
            map.put("id", cartoonVariable.getId());
            map.put("cartoonVariable", cartoonVariable);
            //提交数据，给Pipeline处理
            page.putField("data",map);
            //漫画章节
            }
        }

    }

